import React from 'react';
import { useTemplateContext } from '@/contexts/TemplateContext';
import { toast } from 'sonner';
import { Document, Packer, Paragraph, TextRun, HeadingLevel, AlignmentType, Indent, Spacing, PageSize, LineRuleType } from 'docx';
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';

const ExportPanel: React.FC = () => {
  const { selectedTemplate, templateParams, documentContent } = useTemplateContext();
  
  const handleExportWord = () => {
    if (!selectedTemplate || !documentContent) {
      toast.error('请先选择模板并填写参数');
      return;
    }
    
    // 分离标题和正文内容
    const [title, ...contentLines] = documentContent.split('\n');
    const bodyContent = contentLines.filter(line => line.trim() !== '');
    
    // 创建Word文档
    const doc = new Document({
      sections: [
        {
          properties: {
            page: {
              size: PageSize.A4,
                margins: {
                  top: 1440, // 3.7cm
                  right: 1134, // 2.6cm
                  bottom: 1134, // 2.6cm
                  left: 1417, // 3.7cm
                },
            },
          },
          children: [
            // 添加标题
            new Paragraph({
              children: [
                new TextRun({
                  text: title?.trim() || selectedTemplate.title,
                  font: '黑体',
                  size: 44, // 二号字体
                  bold: true,
                }),
              ],
              alignment: AlignmentType.CENTER,
              spacing: new Spacing({
                after: 200,
              }),
            }),
            
            // 添加正文内容
            ...bodyContent.map(line => new Paragraph({
              children: [
                new TextRun({
                  text: line.trim(),
                  font: '仿宋_GB2312',
                  size: 32, // 三号字体
                }),
              ],
              indent: {
                firstLine: 720, // 首行缩进2字符
              },
      spacing: new Spacing({
        line: 560, // 28磅行距 (28 * 20 = 560 twips)
        lineRule: LineRuleType.EXACT,
        after: 120,
              }),
            })),
          ],
        },
      ],
    });
    
    // 导出Word文档
    Packer.toBlob(doc).then(blob => {
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${selectedTemplate.title}.docx`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
      toast.success('Word文档导出成功');
    }).catch(err => {
      toast.error('导出Word文档失败');
      console.error('Word export error:', err);
    });
  };
  
  const handleExportPdf = () => {
    if (!selectedTemplate || !documentContent) {
      toast.error('请先选择模板并填写参数');
      return;
    }
    
    // 创建PDF文档
    const doc = new jsPDF('p', 'pt', 'a4');
    
    // 获取预览区域并转换为图片
    const previewElement = document.querySelector('.prose.max-w-none');
    if (!previewElement) {
      toast.error('无法找到预览内容');
      return;
    }
    
    // 调整预览区域样式以适应PDF导出
    const originalStyle = (previewElement as HTMLElement).style.cssText;
    (previewElement as HTMLElement).style.width = '595pt'; // A4宽度
    (previewElement as HTMLElement).style.padding = '40px';
    
    html2canvas(previewElement as HTMLElement, {
      scale: 2,
      useCORS: true,
      logging: false
    }).then(canvas => {
      // 恢复原始样式
      (previewElement as HTMLElement).style.cssText = originalStyle;
      
      const imgData = canvas.toDataURL('image/png');
      const imgWidth = 595;
      const imgHeight = canvas.height * imgWidth / canvas.width;
      
      doc.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
      doc.save(`${selectedTemplate.title}.pdf`);
      toast.success('PDF文档导出成功');
    }).catch(err => {
      // 恢复原始样式
      (previewElement as HTMLElement).style.cssText = originalStyle;
      
      toast.error('导出PDF文档失败');
      console.error('PDF export error:', err);
    });
  };
  
  const handleExportParameters = () => {
    if (!selectedTemplate || Object.keys(templateParams).length === 0) {
      toast.error('请先选择模板并填写参数');
      return;
    }
    
    // 导出参数记录
    const paramsText = Object.entries(templateParams)
      .map(([key, value]) => `${key}: ${value}`)
      .join('\n');
      
    const blob = new Blob([paramsText], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${selectedTemplate.title}_参数记录.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    
    toast.success('参数记录导出成功');
  };
  
  return (
    <div className="flex justify-end space-x-4 mt-4">
      <button
        onClick={handleExportWord}
        className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
      >
        <i className="fa-solid fa-file-word mr-2"></i>导出Word文档
      </button>
      <button
        onClick={handleExportPdf}
        className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 transition-colors focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2"
      >
        <i className="fa-solid fa-file-pdf mr-2"></i>导出PDF文档
      </button>
      <button
        onClick={handleExportParameters}
        className="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 transition-colors focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2"
      >
        <i className="fa-solid fa-list mr-2"></i>导出参数记录
      </button>
    </div>
  );
};

export default ExportPanel;